package bcrypt

import (
	"golang.org/x/crypto/bcrypt"
	"sync"
)

// 密码加密工具单例
type PasswordUtil struct{}

var (
	instance *PasswordUtil
	once     sync.Once
)

// GetPasswordUtil 获取单例实例
func GetPasswordUtil() *PasswordUtil {
	once.Do(func() {
		instance = &PasswordUtil{}
	})
	return instance
}

// Encrypt 加密密码 (自动生成salt并包含在结果中)
func (pu *PasswordUtil) Encrypt(password string) (string, error) {
	hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(hashedBytes), err
}

// Verify 验证密码
func (pu *PasswordUtil) Verify(hashedPassword, inputPassword string) bool {
	err := bcrypt.CompareHashAndPassword(
		[]byte(hashedPassword),
		[]byte(inputPassword),
	)
	if err != nil {
		return false
	}
	return true
}
